// 导入数据库操作模块
const db = require('../db/index')

exports.getUser = (req, res) => {
    const sql = 'select id, username, nickname, email, user_pic from ev_users where username=?'
    db.query(sql, req.user.username, (err, result) => {
        if (err) {
            res.err(err.message)
        }
        if (result.length !== 1) {
            res.err('获取用户信息失败')
        }
        res.send({
            state: 200,
            message: '获取成功',
            data: result[0]
        })
    })
}

exports.updateUser = (req, res) => {
    const sql = 'update ev_users set ? where username=?'
    db.query(sql, [req.body, req.body.username], (err, result) => {
        if(err) {
           return res.err(err.message)
        }
        if(result.affectedRows !== 1) {
            return res.err('修改用户信息失败')
        }
        res.err('更改用户信息成功!', 200)
    })
}


// 引入加密中间件

const bcryptjs = require('bcryptjs')

exports.updatePassword = (req, res) => {
    const sql1 = 'select * from ev_users where username=?'
    db.query(sql1, req.user.username, (err, result) => {
        if(err) {
            return res.err(err.message)
        }
        if(result.length !== 1) {
            return res.err('未找到用户')
        }
        const compareword = bcryptjs.compareSync(req.body.oldword, result[0].password)
        if(!compareword) {
            return res.err('密码错误')
        }
        const sql = 'update ev_users set password=? where username=?'
        const newPassword = bcryptjs.hashSync(req.body.newword)
        db.query(sql, [newPassword, req.user.username], (err, result) => {
            if(err) {
                return res.err(err.message)
            }
            if(result.affectedRows !== 1) {
                return res.err('修改密码失败')
            }
            res.err('修改密码成功', 200)
        })
    })
}
